package com.ruoyi.system.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.system.DTO.Reques.partner.PartnerSearchDTO;
import com.ruoyi.system.mapper.PartnerMapper;
import com.ruoyi.system.mapper.VendingMachineMapper;
import com.ruoyi.system.pojo.partner.Partner;
import com.ruoyi.system.pojo.vms.VendingMachine;
import com.ruoyi.system.service.PartnerService;
import com.ruoyi.system.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PartnerServiceImpl implements PartnerService {

    @Autowired
    private PartnerMapper partnerMapper;

    @Autowired
    private VendingMachineMapper vendingMachineMapper;





    @Override
    public PageResult<Partner> searchPartners(PartnerSearchDTO searchDTO) {
        // 设置默认值
        Integer pageIndex = searchDTO.getPageIndex() == null ? 1 : searchDTO.getPageIndex();
        Integer pageSize = searchDTO.getPageSize() == null ? 10 : searchDTO.getPageSize();
        // 创建分页对象
        Page<Partner> page = new Page<>(pageIndex, pageSize);
        // 创建查询条件
        QueryWrapper<Partner> queryWrapper = new QueryWrapper<>();
        if (searchDTO.getName() != null) {
            queryWrapper.like("name", searchDTO.getName());
        }
        // 执行查询
        IPage<Partner> partnerPage = partnerMapper.selectPage(page, queryWrapper);
        //根据id查询vm数量
        List<Partner> records = partnerPage.getRecords();
        for (Partner partner : records) {
            Integer id = partner.getId();
            Long l = vendingMachineMapper.selectCount(new QueryWrapper<VendingMachine>().eq("owner_id", id));
            partner.setVmCount(l.intValue());
        }
        // 构建返回结果
        PageResult<Partner> result = new PageResult<>();
        result.setPageIndex((int) partnerPage.getCurrent());
        result.setPageSize((int) partnerPage.getSize());
        result.setTotalPage((int) partnerPage.getPages());
        result.setTotalCount((int) partnerPage.getTotal());
        result.setCurrentPageRecords(partnerPage.getRecords());

        return result;
    }



}